package com.dong.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dong.service.UserService;
import com.dong.util.Empty;
import com.dong.util.GenerateValidateCode;
import com.dong.vo.User;

public class RegisterServlet extends HttpServlet {	
	
	private static final long serialVersionUID = -1987441146135004339L;


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		
		String message = "";
		//获取客户端参数
		String uid = request.getParameter("uid");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		String tel = request.getParameter("tel");
		String gender = request.getParameter("gender");
		String realName = request.getParameter("realName");
		String question = request.getParameter("question");
		String answer = request.getParameter("answer");
		
		//服务器端验证
		if(Empty.isEmpty(uid) || Empty.isEmpty(password) || Empty.isEmpty(email) || Empty.isEmpty(gender) || 
		   Empty.isEmpty(realName) || Empty.isEmpty(question) || Empty.isEmpty(answer)) {
			
			//这时验证到客户端的有些必填项为空，重新转向注册页面，并显示错误提示
			message = "必填项不能为空，请确认后重新输入！";
			request.setAttribute("message", message);
			request.getRequestDispatcher("userRegister.jsp").forward(request, response);
		} else {   //服务器端验证通过，开始注册
			//生成注册是的邮件激活验证码
			String validateCode = GenerateValidateCode.getValidateCode();
			//新建User对象，并填充
			User user = new User();
			user.setUid(uid);
			user.setPassword(password);
			user.setEmail(email);
			user.setTel(tel);
			user.setGender(Integer.valueOf(gender).intValue());
			user.setRealName(realName);
			user.setQuestion(question);
			user.setAnswer(answer);
			user.setValidateCode(validateCode);
			
			//获取当前应用的路径,用于邮件验证
			String path = request.getContextPath();
	    	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
	    	
			System.out.println(basePath);
			UserService userService = new UserService();
			//UserService方法会跑出异常，这里进行捕捉		
			try {
				userService.addUser(user, basePath);
				//注册成功，转向注册成功页面界面（该页面告诉用户必须邮件激活才能登录)
				message = "恭喜您！注册成功！";
				request.setAttribute("message", message);
				request.getRequestDispatcher("userRegisterSuc.jsp").forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
				//转向错误页面
				message = "服务异常！";
				request.setAttribute("message", message);
				request.getRequestDispatcher("error.jsp").forward(request, response);
			}
		}
	}

}
